
module Blather
class XMPPNode
	## form aggregates fields
	class Form < XMPPNode
		register :x, 'jabber:x:data'

    VALID_TYPES = [:form, :submit, :cancel, :result].freeze

    def title=(title)
			remove_children('title')
      set_content_for :title, title
    end

    def title
      content_from 'ns:title', :ns => self.registered_ns
    end

    def type=(type)
      if type && !VALID_TYPES.include?(type.to_sym)
        raise ArgumentError, "Invalid Type (#{type}), use: #{VALID_TYPES*' '}"
      end
      write_attr :type, type
    end

		def type
			read_attr :type, :to_sym
		end

		def fields
			find('//ns:field',:ns => self.class.registered_ns).map{|f| XMPPNode::Field.new.inherit(f) }
		end

		def submit!(hash)
			self.type = :submit
			hash.each_pair{|k,v| self.set_field!(k.to_s,v) }
		end

		def find_field(var)
			f = find("//ns:field[@var='#{var}']",:ns => self.class.registered_ns).first
			XMPPNode::Field.new.inherit(f) if f
		end

		def set_field!(var,value) 
			tmp_fields = self.fields.map do |f|
				f.value = value if f.var == var
				f
			end
			clear
			tmp_fields.each {|f| self << f } 
		end

		def clear
			remove_children ('field')
		end
	end
end
end
